package com.jalonjia.paste.pojo;

import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class Paste implements Serializable, Delayed {
    private static final long serialVersionUID = 1L;
    private String id = UUID.randomUUID().toString().substring(0, 4);
    private String author;
    private String description;
    private String language;
    private String code;
    private Date expirationTime;

    public void setTimeout(long timeout) {
        this.expirationTime = new Date(System.currentTimeMillis() + timeout);
    }

    /**
     * 以给定的时间单位返回与此对象关联的剩余延迟。
     *
     * @param unit 时间单位
     * @return 剩余的延迟；零或负值表示延迟已经过去
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expirationTime.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 队列里元素的排序依据 一般依据剩余时间排序
     */
    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
    }
}
